<template>
  <div class="news-list">
    <!-- 筛选和搜索区域 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索资讯标题或内容..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-right">
        <el-select v-model="categoryFilter" placeholder="分类" @change="handleFilter">
          <el-option label="全部分类" value="" />
          <el-option label="技术动态" value="技术动态" />
          <el-option label="行业资讯" value="行业资讯" />
          <el-option label="学习资源" value="学习资源" />
          <el-option label="职场发展" value="职场发展" />
          <el-option label="开源项目" value="开源项目" />
        </el-select>
        
        <el-select v-model="sortBy" placeholder="排序" @change="handleSort">
          <el-option label="最新发布" value="latest" />
          <el-option label="最多阅读" value="popular" />
          <el-option label="最多点赞" value="liked" />
          <el-option label="最多评论" value="commented" />
        </el-select>
        
        <el-button @click="toggleViewMode">
          <el-icon v-if="viewMode === 'list'"><Grid /></el-icon>
          <el-icon v-else><List /></el-icon>
          {{ viewMode === 'list' ? '卡片视图' : '列表视图' }}
        </el-button>
      </div>
    </div>

    <!-- 资讯统计 -->
    <div class="news-stats">
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-number">{{ filteredNews.length }}</div>
          <div class="stat-label">资讯总数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ todayCount }}</div>
          <div class="stat-label">今日更新</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ weekCount }}</div>
          <div class="stat-label">本周新增</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ totalViews }}</div>
          <div class="stat-label">总阅读量</div>
        </div>
      </div>
    </div>

    <!-- 资讯列表 -->
    <div class="news-container">
      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'" class="news-list-view">
        <div 
          v-for="news in paginatedNews" 
          :key="news.id"
          class="news-item"
          @click="viewNews(news)"
        >
          <div class="news-image">
            <img :src="news.image" :alt="news.title" />
            <div class="news-category">
              <el-tag :type="getCategoryColor(news.category)" size="small">
                {{ news.category }}
              </el-tag>
            </div>
          </div>
          
          <div class="news-content">
            <h3 class="news-title">{{ news.title }}</h3>
            <p class="news-summary">{{ news.summary }}</p>
            
            <div class="news-meta">
              <div class="meta-left">
                <span class="author">{{ news.author }}</span>
                <span class="publish-time">{{ formatDate(news.publishedAt) }}</span>
              </div>
              <div class="meta-right">
                <span class="read-count">
                  <el-icon><View /></el-icon>
                  {{ news.readCount }}
                </span>
                <span class="like-count">
                  <el-icon><Star /></el-icon>
                  {{ news.likeCount }}
                </span>
                <span class="comment-count">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ news.commentCount }}
                </span>
              </div>
            </div>
          </div>
          
          <div class="news-actions">
            <el-button size="small" @click.stop="toggleLike(news)">
              <el-icon><Star /></el-icon>
              {{ news.isLiked ? '已点赞' : '点赞' }}
            </el-button>
            <el-button size="small" @click.stop="shareNews(news)">
              <el-icon><Share /></el-icon>
              分享
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 卡片视图 -->
      <div v-else class="news-grid-view">
        <div 
          v-for="news in paginatedNews" 
          :key="news.id"
          class="news-card"
          @click="viewNews(news)"
        >
          <div class="card-image">
            <img :src="news.image" :alt="news.title" />
            <div class="card-category">
              <el-tag :type="getCategoryColor(news.category)" size="small">
                {{ news.category }}
              </el-tag>
            </div>
          </div>
          
          <div class="card-content">
            <h4 class="card-title">{{ news.title }}</h4>
            <p class="card-summary">{{ news.summary }}</p>
            
            <div class="card-meta">
              <div class="meta-top">
                <span class="author">{{ news.author }}</span>
                <span class="publish-time">{{ formatDate(news.publishedAt) }}</span>
              </div>
              <div class="meta-bottom">
                <span class="read-count">
                  <el-icon><View /></el-icon>
                  {{ news.readCount }}
                </span>
                <span class="like-count">
                  <el-icon><Star /></el-icon>
                  {{ news.likeCount }}
                </span>
                <span class="comment-count">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ news.commentCount }}
                </span>
              </div>
            </div>
          </div>
          
          <div class="card-footer">
            <el-button size="small" @click.stop="toggleLike(news)">
              <el-icon><Star /></el-icon>
              {{ news.isLiked ? '已点赞' : '点赞' }}
            </el-button>
            <el-button size="small" @click.stop="shareNews(news)">
              <el-icon><Share /></el-icon>
              分享
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredNews.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48, 96]"
          :total="filteredNews.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 空状态 -->
      <div v-if="filteredNews.length === 0" class="empty-state">
        <EmptyState
          image="/images/empty-news.svg"
          title="暂无资讯"
          description="当前筛选条件下没有找到相关资讯"
        >
          <el-button @click="resetFilters">
            重置筛选
          </el-button>
        </EmptyState>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, Grid, List, View, Star, ChatDotRound, Share
} from '@element-plus/icons-vue'
import EmptyState from '@/components/global/EmptyState.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const categoryFilter = ref('')
const sortBy = ref('latest')
const viewMode = ref('list')
const currentPage = ref(1)
const pageSize = ref(12)

// 资讯数据
const newsList = ref([
  {
    id: 1,
    title: 'Vue 3.4 正式发布：性能提升与新特性详解',
    summary: 'Vue.js 团队发布了 3.4 版本，带来了显著的性能提升和多项新特性，包括更好的 TypeScript 支持和组合式 API 优化。',
    category: '技术动态',
    author: '前端技术团队',
    image: '/images/news/vue-3-4.jpg',
    publishedAt: new Date('2024-01-15'),
    readCount: 15420,
    likeCount: 234,
    commentCount: 56,
    isLiked: false
  },
  {
    id: 2,
    title: '2024年前端开发趋势预测：AI驱动的开发体验',
    summary: '随着人工智能技术的快速发展，前端开发正在经历一场革命。本文深入分析了AI如何改变我们的开发方式。',
    category: '行业资讯',
    author: '技术观察员',
    image: '/images/news/ai-frontend.jpg',
    publishedAt: new Date('2024-01-14'),
    readCount: 12350,
    likeCount: 189,
    commentCount: 43,
    isLiked: true
  },
  // 添加更多新闻数据...
  ...Array.from({ length: 48 }, (_, i) => ({
    id: i + 3,
    title: `技术资讯标题 ${i + 3}`,
    summary: `这是第${i + 3}篇技术资讯的摘要内容，介绍了最新的技术动态和发展趋势。`,
    category: ['技术动态', '行业资讯', '学习资源', '职场发展', '开源项目'][Math.floor(Math.random() * 5)],
    author: `作者${i + 3}`,
    image: `/images/news/news-${(i % 10) + 1}.jpg`,
    publishedAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
    readCount: Math.floor(Math.random() * 10000) + 1000,
    likeCount: Math.floor(Math.random() * 500) + 50,
    commentCount: Math.floor(Math.random() * 100) + 10,
    isLiked: Math.random() > 0.7
  }))
])

// 计算属性
const filteredNews = computed(() => {
  let filtered = newsList.value

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(news => 
      news.title.toLowerCase().includes(keyword) ||
      news.summary.toLowerCase().includes(keyword)
    )
  }

  // 分类筛选
  if (categoryFilter.value) {
    filtered = filtered.filter(news => news.category === categoryFilter.value)
  }

  // 排序
  switch (sortBy.value) {
    case 'popular':
      filtered.sort((a, b) => b.readCount - a.readCount)
      break
    case 'liked':
      filtered.sort((a, b) => b.likeCount - a.likeCount)
      break
    case 'commented':
      filtered.sort((a, b) => b.commentCount - a.commentCount)
      break
    default: // latest
      filtered.sort((a, b) => new Date(b.publishedAt) - new Date(a.publishedAt))
  }

  return filtered
})

const paginatedNews = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredNews.value.slice(start, end)
})

const todayCount = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return newsList.value.filter(news => {
    const publishDate = new Date(news.publishedAt)
    publishDate.setHours(0, 0, 0, 0)
    return publishDate.getTime() === today.getTime()
  }).length
})

const weekCount = computed(() => {
  const weekAgo = new Date()
  weekAgo.setDate(weekAgo.getDate() - 7)
  return newsList.value.filter(news => 
    new Date(news.publishedAt) >= weekAgo
  ).length
})

const totalViews = computed(() => {
  return newsList.value.reduce((total, news) => total + news.readCount, 0)
})

// 方法
const getCategoryColor = (category) => {
  const colors = {
    '技术动态': 'primary',
    '行业资讯': 'success',
    '学习资源': 'warning',
    '职场发展': 'info',
    '开源项目': 'danger'
  }
  return colors[category] || 'default'
}

const formatDate = (date) => {
  const now = new Date()
  const diff = now - date
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSort = () => {
  currentPage.value = 1
}

const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'list' ? 'grid' : 'list'
  // 调整分页大小
  if (viewMode.value === 'grid') {
    pageSize.value = 12
  } else {
    pageSize.value = 10
  }
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const resetFilters = () => {
  searchKeyword.value = ''
  categoryFilter.value = ''
  sortBy.value = 'latest'
  currentPage.value = 1
}

const viewNews = (news) => {
  router.push(`/news/detail/${news.id}`)
}

const toggleLike = (news) => {
  news.isLiked = !news.isLiked
  if (news.isLiked) {
    news.likeCount++
    ElMessage.success('点赞成功')
  } else {
    news.likeCount--
    ElMessage.info('取消点赞')
  }
}

const shareNews = (news) => {
  // 复制分享链接到剪贴板
  const shareUrl = `${window.location.origin}/news/detail/${news.id}`
  navigator.clipboard.writeText(shareUrl).then(() => {
    ElMessage.success('分享链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制链接')
  })
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.news-list {
  min-height: 100vh;
  background: var(--el-bg-color-page);
  padding: 20px;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}

.filter-left {
  .el-input {
    width: 300px;
    
    @media (max-width: 1024px) {
      width: 100%;
    }
  }
}

.filter-right {
  display: flex;
  gap: 12px;
  
  @media (max-width: 1024px) {
    flex-wrap: wrap;
  }
  
  .el-select {
    width: 120px;
    
    @media (max-width: 768px) {
      flex: 1;
      min-width: 100px;
    }
  }
}

.news-stats {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 20px;
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  
  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.stat-item {
  text-align: center;
  
  .stat-number {
    font-size: 24px;
    font-weight: 700;
    color: var(--el-color-primary);
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
}

.news-container {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.news-list-view {
  .news-item {
    display: flex;
    gap: 20px;
    padding: 20px 0;
    border-bottom: 1px solid var(--el-border-color-extra-light);
    cursor: pointer;
    transition: background-color 0.3s ease;
    
    &:hover {
      background: var(--el-fill-color-extra-light);
    }
    
    &:last-child {
      border-bottom: none;
    }
    
    .news-image {
      position: relative;
      width: 200px;
      height: 120px;
      border-radius: 8px;
      overflow: hidden;
      flex-shrink: 0;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .news-category {
        position: absolute;
        top: 8px;
        left: 8px;
      }
    }
    
    .news-content {
      flex: 1;
      
      .news-title {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 8px;
        color: var(--el-text-color-primary);
        line-height: 1.4;
      }
      
      .news-summary {
        font-size: 14px;
        color: var(--el-text-color-secondary);
        margin-bottom: 16px;
        line-height: 1.5;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .news-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: var(--el-text-color-placeholder);
        
        .meta-left {
          display: flex;
          gap: 12px;
        }
        
        .meta-right {
          display: flex;
          gap: 16px;
          
          span {
            display: flex;
            align-items: center;
            gap: 2px;
          }
        }
      }
    }
    
    .news-actions {
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-self: flex-start;
    }
  }
}

.news-grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.news-card {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  }
  
  .card-image {
    position: relative;
    height: 180px;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .card-category {
      position: absolute;
      top: 12px;
      left: 12px;
    }
  }
  
  .card-content {
    padding: 16px;
    
    .card-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 8px;
      color: var(--el-text-color-primary);
      line-height: 1.4;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .card-summary {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      margin-bottom: 12px;
      line-height: 1.5;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .card-meta {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
      
      .meta-top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
      }
      
      .meta-bottom {
        display: flex;
        justify-content: space-between;
        
        span {
          display: flex;
          align-items: center;
          gap: 2px;
        }
      }
    }
  }
  
  .card-footer {
    padding: 12px 16px;
    border-top: 1px solid var(--el-border-color-extra-light);
    display: flex;
    gap: 8px;
    
    .el-button {
      flex: 1;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

@media (max-width: 768px) {
  .news-list-view {
    .news-item {
      flex-direction: column;
      
      .news-image {
        width: 100%;
        height: 150px;
      }
      
      .news-actions {
        flex-direction: row;
        align-self: stretch;
        
        .el-button {
          flex: 1;
        }
      }
    }
  }
  
  .news-grid-view {
    grid-template-columns: 1fr;
  }
}
</style>
